package com.featherlike.feather.generator.engine;

import java.io.FileWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.log.NullLogChute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.featherlike.feather.generator.config.Constant;
import com.featherlike.framework.common.util.ClassUtil;
import com.featherlike.framework.common.util.Exceptions;
import com.featherlike.framework.common.util.FileUtil;
import com.featherlike.framework.common.util.IOUtil;
import com.featherlike.framework.common.util.StringUtil;

/**
 * velocity引擎实现
 */
public class VelocityImpl implements ITemplateEngine {
    /**Log**/
    private static final Logger LOGGER = LoggerFactory.getLogger(VelocityImpl.class);
    /**引擎**/
    private static final VelocityEngine ENGINE = new VelocityEngine();

    // 设置 VM 文件加载路径（默认为 classpath）
    public VelocityImpl(String tmplPath) {
        Properties props = new Properties();
        props.setProperty(Velocity.INPUT_ENCODING, Constant.ENCODING_UTF8); // 设置输入字符集
        props.setProperty(Velocity.OUTPUT_ENCODING, Constant.ENCODING_UTF8); // 设置输出字符集
        props.setProperty(Velocity.ENCODING_DEFAULT, Constant.ENCODING_UTF8);
        props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                NullLogChute.class.getName());
        if (StringUtil.isEmpty(tmplPath)) {
            props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,
                    ClassUtil.getClassPath());
        } else {
            props.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, tmplPath);
        }
        ENGINE.init(props);
    }

    @Override
    public void mergeTemplateIntoFile(String vmPath,
            Map<String, Object> dataMap, String filePath) {
        FileWriter writer = null;
        try {
            if (FileUtil.createFile(filePath)) {
                Template template = ENGINE.getTemplate(vmPath);
                VelocityContext context = new VelocityContext(dataMap);
                writer = new FileWriter(filePath);
                template.merge(context, writer);
                writer.close();
            } else {
                LOGGER.info("文件已存在,生成失败");
            }
        } catch (Exception e) {
            LOGGER.error("合并模板出错！", e);
            throw Exceptions.unchecked(e);
        } finally {
            IOUtil.closeQuietly(writer);
        }
    }

    @Override
    public String mergeTemplateReturnString(String vmPath,
            Map<String, Object> dataMap) {
        String result;
        StringWriter writer = null;
        try {
            Template template = ENGINE.getTemplate(vmPath, "ISO-8859-1");
            VelocityContext context = new VelocityContext(dataMap);
            writer = new StringWriter();
            template.merge(context, writer);
            result = writer.toString();

            writer.close();
        } catch (Exception e) {
            LOGGER.error("合并模板出错！", e);
            throw Exceptions.unchecked(e);
        } finally {
            IOUtil.closeQuietly(writer);
        }
        return result;
    }

    @Override
    public String getTemplateSuffix() {
        return Constant.ENGINE_VM_SURFIX;
    }
}
